/*
 * Copyright (C) 2010-2011 sunjumper@163.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package mf.mfrpc.serialize;

import java.io.File;
import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * 文件流数据的适配类。
 */
public class FileDataSourceIterator extends AdapterDataSourceIterator {

    //store datasource for serializable
    private Collection<DataSource> dataSources;

    public FileDataSourceIterator(DataSource... dataSources) {
        this.dataSources = new LinkedHashSet<DataSource>(dataSources.length);
        for (DataSource ds : dataSources) {
            checkAdd(ds);
        }
        dit = this.dataSources.iterator();
    }

    public FileDataSourceIterator(Collection<DataSource> dataSources) {
        super(dataSources);
        this.dataSources = dataSources;
    }

    public FileDataSourceIterator(File... files) {
        dataSources = new LinkedHashSet<DataSource>(3);
        for (File f : files) {
            checkAdd(new FileDataSource(f));
        }
        dit = dataSources.iterator();
    }

    //check dataSources Iterator
    private void checkIterator() {
        if (dit == null) {
            dit = this.dataSources.iterator();
        }
    }

    //don't allow contain the same file datasource with the same input stream
    private void checkAdd(DataSource ds) {
        if (dataSources.contains(ds))
            throw new IllegalArgumentException("don't allow contain the same file datasource with the same input stream");
        dataSources.add(ds);
    }

    @Override
    public boolean hasNext() {
        checkIterator();
        return dit.hasNext();
    }

    @Override
    public DataSource next() {
        checkIterator();
        return dit.next();
    }

    public Collection<DataSource> getDataSources() {
        return dataSources;
    }
}
